package com.util;

import java.math.BigDecimal;
import java.text.*;
import java.sql.*;

import java.util.regex.Matcher; 
import java.util.regex.Pattern; 
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.TimeZone;
import java.util.UUID;

@SuppressWarnings({ "rawtypes", "unchecked" })
public class XDataConvert {

	public static java.sql.Timestamp GetNowDate() {
		java.text.SimpleDateFormat df = new java.text.SimpleDateFormat("yyyy-MM-dd"); 
		java.util.Calendar c = java.util.Calendar.getInstance();		
		java.sql.Timestamp dt = java.sql.Timestamp.valueOf(df.format(c.getTime()));
		return dt;
	}
	public static java.sql.Timestamp GetDefDate() {
		java.sql.Timestamp def = java.sql.Timestamp.valueOf("1900-01-01 00:00:00");
		return def;
	}

	public static String GetUUIDtoString(){
		String uuid = "";
		UUID uu = UUID.randomUUID();
		uuid = uu.toString().replace("-", "");
		return uuid;
	}
	
	public static int TryToInt(Object val ) {
		return TryToInt(val,0);
	}
	
	public static String MaxUsersYhxh(){
		java.text.SimpleDateFormat df = new java.text.SimpleDateFormat("dd HH:mm:ss"); 
		java.util.Calendar c = java.util.Calendar.getInstance();
		String  now_date = df.format(c.getTime());
		return now_date.replace(":", "").replace(" ", "");
	}
	
	public static int TryToInt(Object val ,int def) {
		if( val == null || "".equals(val)  )
			return def;
		String str = (""+val).trim();
		if( "".equals(str)  )
			return def;
		try {
			return new Integer(str).intValue();
		} catch (Exception ex) {
			System.out.println(" 警告TryToInt异常!Class["+ val.getClass() +"]val["+val+"]");
		}
		return def;
	}
	

	public static double TryToDouble(Object val ) {
		return TryToDouble(val,0);
	}
	public static double TryToDouble(Object val,double def) {
		if( val == null || "".equals(val) || "?".equals(val) )//|| "%".equals(val) 
			return def;
		String str = (""+val).replaceAll(",","").trim();
		if( str.length()==0  )
			return def;
		try {
			return new Double(str ).doubleValue();
		} catch (Exception ex) {
			System.out.println(" 警告：TryToDouble转换失败！Class["+ val.getClass() +"]val["+val+"]");
		}
		return def;
	}

	public static BigDecimal TryToBigDecimal(Object val) {
		return TryToBigDecimal(val,0);
	}
	public static BigDecimal TryToBigDecimal(Object val, double def) {
		if( val == null || "".equals(val)  )
			return new BigDecimal(def);
		String str = (""+val).trim();
		if( "".equals(str)  )
			return new BigDecimal(def);
		try {
			return new BigDecimal(str );
		} catch (Exception ex) {
			System.out.println(" 警告TryToBigDecimal异常!Class["+ val.getClass() +"]val["+val+"]");
		}
		return new BigDecimal(def);
	}
	
	public static long TryToLong(Object val) {
		return TryToLong(val,0);
	}
	public static long TryToLong(Object val, long def) {
		if( val == null || "".equals(val)|| "null".equals(val)  )
			return def;
		String str = (""+val).trim();
		if( "".equals(str)  )
			return def;
		try {
			return new Long(str ).longValue();
		} catch (Exception ex) {
			System.out.println(" 警告TryToLong异常!Class["+ val.getClass() +"]val["+val+"]");
		}
		return def;
	}


	public static java.sql.Timestamp TryToDate(Object val) {
		java.sql.Timestamp def = GetDefDate();
		return TryToDate(val, def);
	}

	public static java.sql.Timestamp TryToDate(Object val,java.sql.Timestamp def) {
		if (val == null || "".equals(val))
			return def;
		String str = (""+val).trim();
		if( "".equals(str)  )
			return def;
		java.sql.Timestamp ts = def;
		if (val instanceof java.lang.String){
			try {
				//String str = (String) val;
				if (str.length()==10
						&& ((str.charAt(4) == '-' && str.charAt(7) == '-'))) {
					ts = java.sql.Timestamp.valueOf(str +" 00:00:00");
					return ts;
				}else if (str.length()==8 && str.indexOf("-")<0) {
					SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
					java.util.Date d = sdf.parse(str);
					ts = new java.sql.Timestamp(d.getTime());
					return ts;
				}
				ts = java.sql.Timestamp.valueOf(val.toString());
			} catch (Exception ex) {
				return def;
			}
		}else if (val instanceof java.sql.Timestamp){
			ts = (java.sql.Timestamp) val;
		}else if (val instanceof java.sql.Date){
			ts = new java.sql.Timestamp( ((java.sql.Date)val).getTime() );
		}else if (val instanceof java.util.Date){
			ts = new java.sql.Timestamp( ((java.util.Date)val).getTime() );
		} else {
			System.out.println(" 警告TryToDate异常!Class["+ val.getClass() +"]val["+val+"]");
		}
		return ts;
	}

	public static String TryToString(Object val) {
		if (val == null)
			return "";
		return val.toString();
	}

	// 加工为HTML字符串
	public static String toHTMLString(Object val) {
		if (val == null || "".equals(val)||"&nbsp;".equals(val))
			return "&nbsp;";
		return val.toString();
	}
	// 加工为浮点数，保持两位小数点，不显示0（即：为0时显示空格）
	public static String toHTMLStringNo0(Object val) {
		if (val == null || "".equals(val)||"&nbsp;".equals(val))
			return "&nbsp;";
		if("0".equals(""+val) || "0.0".equals(""+val) || "0.00".equals(""+val)){
			return "&nbsp;";
		}
		return val.toString();
	}

	// 加工为HTML字符串--日期
	public static String toHTMLDateString(Object val) {
		if (val == null || "".equals(val)||"&nbsp;".equals(val))
			return "&nbsp;";
		return XDataConvert.TryToDateString(val);
	}
	// 加工为HTML字符串--日期时间
	public static String toHTMLDateTimeString(Object val) {
		if (val == null || "".equals(val)||"&nbsp;".equals(val))
			return "&nbsp;";
		return XDataConvert.TryToDateTimeString(val);
	}
	// 加工为HTML字符串--时间
	public static String toHTMLTimeString(Object val) {
		if (val == null || "".equals(val)||"&nbsp;".equals(val))
			return "&nbsp;";
		return XDataConvert.TryToTimeString(val);
	}
	// 加工为浮点数，保持两位小数点
	public static String toHTMLDecimal(long val) {
		DecimalFormat fmt = new java.text.DecimalFormat("0.00");
		return fmt.format(val);
	}
	// 加工为浮点数，保持两位小数点
	public static String toHTMLDecimal(double val) {
		DecimalFormat fmt = new java.text.DecimalFormat("0.00");
		return fmt.format(val);
	}
	// 加工为浮点数，保持两位小数点
	public static String toHTMLDecimal(Object val) {
		if (val == null || "".equals(val)||"&nbsp;".equals(val))
			return "&nbsp;";
		DecimalFormat fmt = new java.text.DecimalFormat("0.00");
		return fmt.format(TryToDouble(val));
	}
	// 加工为浮点数，保持两位小数点
	public static String toHTMLDecimalDef0(Object val) {
		if (val == null || "".equals(val)||"&nbsp;".equals(val))
			return "0.00";
		DecimalFormat fmt = new java.text.DecimalFormat("0.00");
		return fmt.format(TryToDouble(val));
	}
	// 加工为浮点数，保持两位小数点，不显示0（即：为0时显示空格）
	public static String toHTMLDecimalNo0(Object val) {
		if (val == null || "".equals(val)||"&nbsp;".equals(val))
			return "&nbsp;";
		DecimalFormat fmt = new java.text.DecimalFormat("0.00");
		double d = TryToDouble(val);
		if(d==0)
			return "&nbsp;";
		return fmt.format(d);
	}
	// 加工为浮点数，保持指定精度
	public static String toHTMLDecimal(Object val,int len) {
		if (val == null || "".equals(val)||"&nbsp;".equals(val))
			return "&nbsp;";
		String jd="0";
		int t = len;
		while(t>0){
			if(jd.length()==1) jd += ".";
			jd += "0";
			t--;
		}
		DecimalFormat fmt = new java.text.DecimalFormat(jd);
		return fmt.format(TryToDouble(val));
	}

	// 加工为万元，空值显示空格，保持两位小数点
	public static String toHTMLWanYuanValue(Object val) {
		if (val == null || "".equals(val)||"&nbsp;".equals(val))
			return "&nbsp;";
		DecimalFormat fmt = new java.text.DecimalFormat("0.00");
		return fmt.format(TryToDouble(val) / 10000);
	}

	// 加工为万元自动加逗号，空值显示空格，保持两位小数点
	public static String toHTMLWanYuan(Object val) {
		if (val == null || "".equals(val)||"&nbsp;".equals(val))
			return "&nbsp;";
		DecimalFormat fmt = new java.text.DecimalFormat(",##0.00");
		return fmt.format(TryToDouble(val) / 10000);
	}

	// 加工为万元自动加逗号，空值显示0，保持两位小数点
	public static String toValueWanYuan(Object val) {
		if (val == null || "".equals(val))
			return "0";
		DecimalFormat fmt = new java.text.DecimalFormat(",##0.00");
		return fmt.format(TryToDouble(val) / 10000);
	}

	// 加工为百分比，保持两位小数点
	public static String toHTMLBaiFenBi(Object val) {
		if (val == null || "".equals(val)||"&nbsp;".equals(val))
			return "&nbsp;";
		DecimalFormat fmt = new java.text.DecimalFormat(",##0.00");
		return fmt.format(TryToDouble(val) * 100);
	}
	// 按格式加工
	public static String toHTMLDecFormat(Object val ,String str_fmt) {
		if (val == null || "".equals(val)||"&nbsp;".equals(val))
			return "&nbsp;";
		DecimalFormat fmt = new java.text.DecimalFormat(str_fmt);
		return fmt.format(TryToDouble(val));
	}
	// 按格式加工，零则返回空格
	public static String toHTMLDecFormatNo0(Object val ,String str_fmt) {
		if (val == null || "".equals(val)||"&nbsp;".equals(val))
			return "&nbsp;";
		double d = TryToDouble(val);
		if(d==0)
			return "&nbsp;";
		DecimalFormat fmt = new java.text.DecimalFormat(str_fmt);
		return fmt.format(d);
	}

	// 加工为元，空值显示空格，保持两位小数点
	public static String toHTMLYuan(Object val) {
		if (val == null || "".equals(val)||"&nbsp;".equals(val))
			return "&nbsp;";
		DecimalFormat fmt = new java.text.DecimalFormat(",##0.00");
		return fmt.format(TryToDouble(val));
	}

	// 加工为元，空值显示0，保持两位小数点
	public static String toValueYuan(Object val) {
		if (val == null || "".equals(val)||"&nbsp;".equals(val))
			return "0";
		DecimalFormat fmt = new java.text.DecimalFormat(",##0.00");
		return fmt.format(TryToDouble(val));
	}

	// 0或原值，空值显示0
	public static String toValue(Object val) {
		if (val == null || "".equals(val)||"&nbsp;".equals(val))
			return "0";
		return "" + val;
	}

	// new java.text.DecimalFormat("#.00").format(3.1415926)

	public static String pintColorFmt(Object val) {
		if(val==null || "".equals(val)||"&nbsp;".equals(val)){
			return "&nbsp;";
		}
		String txt = new String("");

		DecimalFormat fmt = new java.text.DecimalFormat(",##0.00");
		if ( "".equals(val))
			txt = "&nbsp;";
		else {
			double num = Double.parseDouble(val.toString());
			if (num < 0)
				txt = "<font color=\"#FF0000\">" + fmt.format(num) + "</font>";
			else
				txt = fmt.format(num);
		}
		return txt;
	}

	public static String pintColor(double val) {
		if ( val < 0)
			return "<font color=\"#FF0000\">" + toHTMLDecimal(val) + "</font>";
		else
			return toHTMLDecimal(val);
	}
	public static String pintColor(Object val) {
		String txt = new String("");
		if (val==null || "".equals(val)||"&nbsp;".equals(val))
			txt = "&nbsp;";
		else {
			if ( TryToDouble(val) < 0)
				txt = "<font color=\"#FF0000\">" + toHTMLDecimal(val) + "</font>";
			else
				txt = toHTMLDecimal(val);
		}
		return txt;
	}

	public static String pintColor(Object val, String color) {
		String txt = new String("");
		if (val==null || "".equals(val)||"&nbsp;".equals(val))
			txt = "&nbsp;";
		else {
			if (TryToDouble(val) < 0)
				txt = "<font color=\"" + color + "\">" + val + "</font>";
			else
				txt = "" + val;
		}
		return txt;
	}

	
	public static String CharSetISOtoGB(String iso) {
		String gb;
        try {
        	if (iso.equals("") || iso == null) {
        		return "";
        	} else {
        		iso = iso.trim();
        		gb = new String(iso.getBytes("ISO-8859-1"), "GB2312");
        		return gb;
        	}
        } catch (Exception e) {
        	System.err.print("编码转换错误：" + e.getMessage());
        	return "";
        }
	}
	
	public static String toUtf8String(String s) {
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < s.length(); i++) {
			char c = s.charAt(i);
			if (c >= 0 && c <= 255) {
				sb.append(c);
			} else {
				byte[] b;
				try {
					b = Character.toString(c).getBytes("UTF-8");
				} catch (Exception ex) {
					System.out.println(ex);
					b = new byte[0];
				}
				for (int j = 0; j < b.length; j++) {
					int k = b[j];
					if (k < 0)
						k += 256;
					sb.append("%" + Integer.toHexString(k).toUpperCase());
				}
			}
		}
		return sb.toString();
	}

	public static String trimSpace(String str) {
		String tmp = str.replaceAll(" ", "")
						.replaceAll("　", "")
						.replaceAll("&nbsp;", "")
						.trim();
		return tmp;		
	}
	public static String trimToNumber(String str) {
		String tmp = str.replaceAll(" ", "")
						.replaceAll("　", "")
						.replaceAll("&nbsp;", "")
						.replaceAll(",", "")
						.replaceAll("#", "")
						.replaceAll("$", "")
						.replaceAll("＄", "")
						.replaceAll("％", "")
						.replaceAll("%", "")
						.replaceAll("￥", "")
						.trim();
		return tmp;		
	}

	/*
	 * 获取当前时间字符串，指定格式
	 */
	public static String NowString(String format){
		java.text.SimpleDateFormat df = new java.text.SimpleDateFormat(format); 
		java.util.Calendar c = java.util.Calendar.getInstance();
		String str = df.format(c.getTime());
		return str;
	}
    //将日期转化为大小写  
    public static String dateToUpper(Object val){
        String res="";  
        Timestamp date = XDataConvert.TryToDate(val);
        if(date!=null){  
        	java.util.Calendar ca = java.util.Calendar.getInstance();  
            ca.setTime(date);  
            int year = ca.get(java.util.Calendar.YEAR);  
            int month = ca.get(java.util.Calendar.MONTH) + 1;  
            int day = ca.get(java.util.Calendar.DAY_OF_MONTH);  
            res=numToUpper(year) + "年" + monthToUppder(month) + "月"+dayToUppder(day) + "日";  
        }  
        return res; 
    }
    // 将当前日期转化为大小写  
    public static String NowDateToUpper() {  
        String rtn="";  
        java.util.Calendar ca = java.util.Calendar.getInstance();
        int year = ca.get(java.util.Calendar.YEAR);  
        int month = ca.get(java.util.Calendar.MONTH) + 1;  
        int day = ca.get(java.util.Calendar.DAY_OF_MONTH);  
        rtn=numToUpper(year) + "年" + monthToUppder(month) + "月"+dayToUppder(day) + "日";  
        return rtn;  
    }
  
    // 将数字转化为大写  
    public static String numToUpper(int num) {  
        // String u[] = {"零","壹","贰","叁","肆","伍","陆","柒","捌","玖"};  
        String u[] = { "〇", "一", "二", "三", "四", "五", "六", "七", "八", "九" };  
        char[] str = String.valueOf(num).toCharArray();  
        String rstr = "";  
        for (int i = 0; i < str.length; i++) {  
            rstr = rstr + u[Integer.parseInt(str[i] + "")];  
        }  
        return rstr;  
    }  
  
    // 月转化为大写  
    private static String monthToUppder(int month) {  
        if (month < 10) {  
            return numToUpper(month);  
        } else if (month == 10) {  
            return "十";  
        } else {  
            return "十" + numToUpper(month - 10);  
        }  
    }  
  
    // 日转化为大写  
    private static String dayToUppder(int day) {  
        if (day < 20) {  
            return monthToUppder(day);  
        } else {  
            char[] str = String.valueOf(day).toCharArray();  
            if (str[1] == '0') {  
                return numToUpper(Integer.parseInt(str[0] + "")) + "十";  
            } else {  
                return numToUpper(Integer.parseInt(str[0] + "")) + "十"  
                        + numToUpper(Integer.parseInt(str[1] + ""));  
            }  
        }  
    }  
	
	public static String NowYear(){//年度
		java.text.SimpleDateFormat df = new java.text.SimpleDateFormat("yyyy"); 
		java.util.Calendar c = java.util.Calendar.getInstance();
		String  now_date = df.format(c.getTime());
		return now_date.substring(0, 4);
	}

	public static String NowDateStringYY(){
		java.text.SimpleDateFormat df = new java.text.SimpleDateFormat("yyyy-MM-dd"); 
		java.util.Calendar c = java.util.Calendar.getInstance();
		String  now_date = df.format(c.getTime());
		return now_date.substring(0, 4) +"-01-01";
	}
	public static String NowDateStringMM(){
		java.text.SimpleDateFormat df = new java.text.SimpleDateFormat("yyyy-MM-dd"); 
		java.util.Calendar c = java.util.Calendar.getInstance();
		String  now_date = df.format(c.getTime());
		return now_date.substring(0, 7) +"-01";
	}
	public static String NowDateString() {
		java.text.SimpleDateFormat df = new java.text.SimpleDateFormat("yyyy-MM-dd"); 
		java.util.Calendar c = java.util.Calendar.getInstance();
		String  now_date = df.format(c.getTime());
		return now_date;
	}
	public static String NowTimeString() {
		java.text.SimpleDateFormat df = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 
		java.util.Calendar c = java.util.Calendar.getInstance();
		String  now_date = df.format(c.getTime());
		return now_date;
	}
	public static String NowTimeMString() {
		java.text.SimpleDateFormat df = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS"); 
		java.util.Calendar c = java.util.Calendar.getInstance();
		String  now_date = df.format(c.getTime());
		return now_date;
	}
	/**
	 * 获取日期时间前十位yyyyMMddHH
	 * @return
	 */
	public static String NowTimeString10() {
		java.text.SimpleDateFormat df = new java.text.SimpleDateFormat("yyyyMMddHHmmss"); 
		java.util.Calendar c = java.util.Calendar.getInstance();
		String  now_date = df.format(c.getTime());
		return now_date.substring(0,10);
	}
	public static String TryToDateString(Object val) {
		if (val == null || "".equals(val))
			return "";
		java.sql.Timestamp def = GetDefDate();
		java.sql.Timestamp dt = TryToDate(val, def);
		if(dt==def) {
			return "";
		}else{
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			return sdf.format(dt);
		}
	}
	public static String TryToTimeString(Object val) {
		if (val == null || "".equals(val))
			return "";
		java.sql.Timestamp def = GetDefDate();
		java.sql.Timestamp dt = TryToDate(val, def);
		if(dt==def) {
			return "";
		}else{
			SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
			return sdf.format(dt);
		}
	}
	public static String TryToTimeByHS(Object val) {
		if (val == null || "".equals(val))
			return "";
		java.sql.Timestamp def = GetDefDate();
		java.sql.Timestamp dt = TryToDate(val, def);
		if(dt==def) {
			return "";
		}else{
			SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
			return sdf.format(dt);
		}
	}
	public static String TryToDateTimeString(Object val) {
		if (val == null || "".equals(val)||"&nbsp;".equals(val))
			return "&nbsp;";
		java.sql.Timestamp def = GetDefDate();
		java.sql.Timestamp dt = TryToDate(val, def);
		if(dt==def) {
			return "&nbsp;";
		}else{
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			return sdf.format(dt).replaceAll(" 00:00:00", "");
		}
	}
	public static String toHTMLDate(Object val) {
		if (val == null || "".equals(val)||"&nbsp;".equals(val))
			return "&nbsp;";
		java.sql.Timestamp def = GetDefDate();
		java.sql.Timestamp dt = TryToDate(val, def);
		if(dt==def) {
			return "&nbsp;";
		}else{
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			return sdf.format(dt);
		}
	}
	public static String toHTMLDateTime(Object val) {
		if (val == null || "".equals(val)||"&nbsp;".equals(val))
			return "&nbsp;";
		java.sql.Timestamp def = GetDefDate();
		java.sql.Timestamp dt = TryToDate(val, def);
		if(dt==def) {
			return "&nbsp;";
		}else{
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			return sdf.format(dt).replaceAll(" 00:00:00", "");
		}
	}

	/**
	 * 获取当前指定格式的当前时间字符串
	 * @param dateformat
	 * @return
	 */
	public static String getNowString(String dateformat) {
		java.text.SimpleDateFormat df = new java.text.SimpleDateFormat(dateformat); 
		java.util.Calendar c = java.util.Calendar.getInstance();
		String  date = df.format(c.getTime());
		return date;
	}
	/**
	 * 将日期转换为指定格式的字符串
	 * @param dateformat
	 * @return
	 */
	public static String dateToString(String date,String to_dateformat) {
		java.text.SimpleDateFormat df = new java.text.SimpleDateFormat(to_dateformat); 
		String  str = df.format( TryToDate(date) );
		return str;
	}
	/**
	 * 将日期转换为指定格式的字符串
	 * @param dateformat
	 * @return
	 */
	public static String dateToString(java.sql.Timestamp date,String to_dateformat) {
		java.text.SimpleDateFormat df = new java.text.SimpleDateFormat(to_dateformat); 
		String  str = df.format( date );
		return str;
	}
	/**
	 * 将日期转换为指定格式的字符串
	 * @param dateformat
	 * @return
	 */
	public static String dateToString(java.sql.Date date,String to_dateformat) {
		java.text.SimpleDateFormat df = new java.text.SimpleDateFormat(to_dateformat); 
		String  str = df.format( date );
		return str;
	}

	public static boolean toBoolean(Object val) {
		if(val==null)
			return false;
		String tmp = val.toString().toUpperCase();
		if("1".equals(tmp) 
				|| "ON".equals(tmp)
				|| "Y".equals(tmp)
				|| "YES".equals(tmp)
				|| "T".equals(tmp)
				|| "TRUE".equals(tmp)
				|| "CHECKED".equals(tmp)
				|| "SELECTED".equals(tmp)
			){
			return true;
		}
		return false;
	}

	/**
	 * 获取固定长度的字符串
	 * @param val
	 * @param len
	 * @return
	 * @throws Exception
	 */
	public static String getHtmlFixLen(Object val,int len) throws Exception {
		if (val == null || "".equals(val)){
			return "&nbsp;";
		}
		String mc=val.toString().trim();
		if(mc.length()>len){
			String click = "if(this.innerHTML!=this.title){this.innerHTML=this.title;}else{this.innerHTML=this.title.substring(0,"+len+")+\"...\";}"; 
			mc="<span title=\""+mc+"\" onclick='"+click+"'>"+ mc.substring(0,len)+"...</span>";
		}
		return mc;
	}
	public static String leftPad(String str ,int len,String pad ){
		if(str==null) return null;
		if(str.length()==len) return str;
		if(str.length()>len){
			return str.substring(0,len);
		}
		String tmp = str;
		while(tmp.length()<len){
			tmp = pad + tmp;
		}
		if(tmp.length()>len){
			tmp = tmp.substring(0,len-str.length()) + str;
		}
		return tmp;
	}
	public static String rightPad(String str ,int len,String pad ){
		if(str==null) return null;
		if(str.length()==len) return str;
		if(str.length()>len){
			return str.substring(0,len);
		}
		String tmp = str;
		while(tmp.length()<len){
			tmp = tmp + pad;
		}
		if(tmp.length()>len){
			tmp = tmp.substring(0,len);
		}
		return tmp;
	}

	/**
	 * 在一段内容content搜索中获取一部分
	 * 这一部分内容必须在start之后，end之前（除非end为null）
	 * @param content
	 * @param start
	 * @param end
	 * @return
	 */
    public static String partString(String content, String start, String end)
    {
        String rtn = "";
        int s = content.indexOf(start);
        if (s == -1){
            rtn = "";
        }else{
			if (end == null){// null时可在没有问号情况下取值到最后
				rtn = content.substring(s + start.length());
			} else {
				int e = content.indexOf(end, s + start.length());
				if (e < s) {
					rtn = "";
				} else {
					rtn = content.substring(s + start.length(), e);
				}
			}
        }
        return rtn;
    }
    /**
     * 在一段内容content搜索中获取一部分，
     * 这一部分内容必须在start0的start1之后与end之间
     * 如果找不到start0或找不到end，则返回空窜
     * start0与end之间如果找不到start1，则返回start0与end之间的部分内容
     * @param content
     * @param start0
     * @param start1
     * @param end
     * @return
     */
    public static String partString(String content, String start0, String start1, String end)
    {
    	String rtn = "";
    	int s0 = content.indexOf(start0);
    	if (s0 == -1){
    		rtn = "";
    	}else if(start1==null){
			int e = content.indexOf(end, s0 + start0.length());
			if (e < s0) {
				rtn = "";
			} else {
				rtn = content.substring(s0 + start0.length(), e);
			}
    	}else if(start1!=null){
    		int s1 = content.indexOf(start1, s0 + start0.length());
    		if(s1<=0){
    			rtn = "";
    		}else{
				int e = content.indexOf(end, s1 + start1.length());
				if (e < s1) {
					rtn = "";
				} else {
					rtn = content.substring(s0 + start0.length(), e);
				}
    		}
    	}
    	return rtn;
    }


	public static String getXZQH_JM(String xzqh_dm) {
		String jm = xzqh_dm;
		while(jm.endsWith("00")){
			jm = jm.substring(0, jm.length() - 2);
		}
		return jm;
	}

	public static double getLV(double fz,double fm ) {
		if(fm==0)
			return 0;
		return fz/fm;
	}
	public static double getLV(Object fz,Object fm ) {
		return getLV( TryToDouble(fz) ,TryToDouble(fm) );
	}
	public static String getLastMonth_YYYY() {
		//上一月份对应的年度
		java.text.SimpleDateFormat df = new java.text.SimpleDateFormat("yyyyMMdd"); 
		java.util.Calendar c = java.util.Calendar.getInstance(); 
		c.add(java.util.Calendar.MONTH,-1);
		String  now_date = df.format(c.getTime());
		return now_date.substring(0,4);
	}
	public static String getLastMonth_MM() {
		//上一月份
		java.text.SimpleDateFormat df = new java.text.SimpleDateFormat("yyyyMMdd"); 
		java.util.Calendar c = java.util.Calendar.getInstance(); 
		c.add(java.util.Calendar.MONTH,-1);
		String  now_date = df.format(c.getTime());
		return now_date.substring(4,6);
	}
	public static String getLastMonth_DateBegin() {
		//上一月份的第一天的日期
		java.text.SimpleDateFormat df = new java.text.SimpleDateFormat("yyyy-MM-dd"); 
		java.util.Calendar c = java.util.Calendar.getInstance(); 
		c.add(java.util.Calendar.MONTH,-1);
		String  now_date = df.format(c.getTime());
		return now_date.substring(0,7)+"-01";
	}
	public static String getLastMonth_DateEnd() {
		//上一月份的最后一天的日期
		java.text.SimpleDateFormat df = new java.text.SimpleDateFormat("yyyy-MM-dd"); 
		java.util.Calendar c = java.util.Calendar.getInstance(); 
		int d = (int) XDataConvert.TryToLong(new java.text.SimpleDateFormat("dd").format(c.getTime()));
		c.add(java.util.Calendar.DATE,-d);
		String  now_date = df.format(c.getTime());
		return now_date;
	}
	
	public static void sortLong(HashMap map ){
		if(map==null){
			return;
		}
		long[] list = new long[map.size()];
		int i=0;
		Iterator it = map.entrySet().iterator();
		while (it.hasNext()) {
			Map.Entry e = (Map.Entry) it.next();
			list[i]=XDataConvert.TryToLong(e.getKey());
			i++;
		}
		Arrays.sort(list);
		for(i=0;i<list.length;i++){
			map.put(""+list[i],""+(list.length-i));
		}
	}
	public static void sortDouble(HashMap map ){
		if(map==null){
			return;
		}
		double[] list = new double[map.size()];
		int i=0;
		Iterator it = map.entrySet().iterator();
		while (it.hasNext()) {
			Map.Entry e = (Map.Entry) it.next();
			list[i]=XDataConvert.TryToDouble(e.getKey());
			i++;
		}
		Arrays.sort(list);
		for(i=0;i<list.length;i++){
			map.put(""+list[i],""+(list.length-i));
		}
	}
	public static void sortString(HashMap map ){
		if(map==null){
			return;
		}
		String[] list = new String[map.size()];
		int i=0;
		Iterator it = map.entrySet().iterator();
		while (it.hasNext()) {
			Map.Entry e = (Map.Entry) it.next();
			list[i]=""+e.getKey();
			i++;
		}
		Arrays.sort(list);
		for(i=0;i<list.length;i++){
			map.put(""+list[i],""+(list.length-i));
		}
	}

	public static String toSqlInValues(String strs ){
		String[] vals = strs.split(",");
		String in_str = "";
		for(int i=0;i<vals.length;i++){
			if(in_str.length()==0){
				in_str += "'"+vals[i]+"'";
			}else{
				in_str += ",'"+vals[i]+"'";
			}
		}
		return in_str;
	}
	
	public static String s2hms(Object val){
		return s2hms(val,"CN");
	}
	
	//格式化秒数为 时、分、秒
	public static String s2hms(Object val,String flag){
		String str = "";
		if (val == null || "".equals(val)||"&nbsp;".equals(val))
			return "&nbsp;";
		else {
			str = val.toString();
		}
		 long hour = Long.parseLong(str)/(60*60);
		 long minute = (Long.parseLong(str) - hour*60*60)/(60);
		 long second = (Long.parseLong(str) - hour*60*60 - minute*60);
		 if(second >= 60 )
		 {
		   second = second % 60;
		   minute+=second/60;
		 }
		 if(minute >= 60)
		 {
		   minute = minute %60;
		   hour += minute/60;
		 }
		 String sh = "";
		 String sm ="";
		 String ss = "";
		 if(hour <10)
		 {
		    sh = "0" + String.valueOf(hour);
		 }else
		 {
		    sh = String.valueOf(hour);
		 }
		 if(minute <10)
		 {
		    sm = "0" + String.valueOf(minute);
		 }else
		 {
		    sm = String.valueOf(minute);
		 }
		 if(second <10)
		 {
		    ss = "0" + String.valueOf(second);
		 }else
		 {
		    ss = String.valueOf(second);
		 }
		 String rtn = "";
		 if("EN".equals(flag.toUpperCase())){
			 rtn = sh +":"+ sm +":"+ ss ;
		 }else{
			 rtn = sh +"小时"+ sm +"分"+ ss +"秒";
		 }
		return rtn;
	}
	
	//去掉文本中的html标签 转换为普通字符串
	public static String dropHTMLTag(Object val){ 
		String htmlStr = "";
		if (val == null || "".equals(val)||"&nbsp;".equals(val))
			return "&nbsp;";
		else {
			htmlStr = val.toString();
		}
        String regEx_script="<script[^>]*?>[\\s\\S]*?<\\/script>"; //定义script的正则表达式 
        String regEx_style="<style[^>]*?>[\\s\\S]*?<\\/style>"; //定义style的正则表达式 
        String regEx_html="<[^>]+>"; //定义HTML标签的正则表达式 
        
        Pattern p_script=Pattern.compile(regEx_script,Pattern.CASE_INSENSITIVE); 
        Matcher m_script=p_script.matcher(htmlStr); 
        htmlStr=m_script.replaceAll(""); //过滤script标签 
        
        Pattern p_style=Pattern.compile(regEx_style,Pattern.CASE_INSENSITIVE); 
        Matcher m_style=p_style.matcher(htmlStr); 
        htmlStr=m_style.replaceAll(""); //过滤style标签 
        
        Pattern p_html=Pattern.compile(regEx_html,Pattern.CASE_INSENSITIVE); 
        Matcher m_html=p_html.matcher(htmlStr); 
        htmlStr=m_html.replaceAll(""); //过滤html标签 

       return htmlStr.replaceAll("&nbsp;", "").replaceAll(" ",""); //返回文本字符串 
    } 
	

	public static String getDateTimeString(Object val, String format) {
		java.text.SimpleDateFormat df = new java.text.SimpleDateFormat(format);
		TimeZone zone = TimeZone.getTimeZone("GMT+8");
		df.setTimeZone(zone);
		java.sql.Timestamp dt=TryToDate(val);
		String now_date = df.format(dt.getTime());
		return now_date;
	}

	public static String getStringNotNull(String str){
		if(str==null)return"";
		if(str.equals("null"))return "";
		if(str.equals("%"))return "";
		return str.trim();
	}

	public static void main(String[] arr){		
		System.out.println(GetUUIDtoString());
	}
	
	public static String toHTMLDecimalDef0(Object val,String fmtType) {
		if (val == null || "".equals(val)||"&nbsp;".equals(val))
			return "0.00";
		if("".equals(fmtType)) fmtType = "0.00";
		DecimalFormat fmt = new java.text.DecimalFormat(fmtType);
		return fmt.format(TryToDouble(val));
	}
	
	public static String toHTMLDecimalNo0(Object val,String fmtType) {
		if (val == null || "".equals(val)||"&nbsp;".equals(val))
			return "&nbsp;";
		if("".equals(fmtType)) fmtType = "0.00";
		DecimalFormat fmt = new java.text.DecimalFormat(fmtType);
		double d = TryToDouble(val);
		if(d==0)
			return "&nbsp;";
		return fmt.format(d);
	}
	
	/**
	 * 小写金额转换为大些的方法
	 * jushaopeng
	 */
	
	
    private static final String NUM = "零壹贰叁肆伍陆柒捌玖";   
    private static final String UNIT = "仟佰拾个";   
    private static final String GRADEUNIT = "仟万亿兆";   
    private static final String DOTUNIT = "角分厘";   
    private static final int GRADE = 4;  
    private static final NumberFormat nf = new DecimalFormat("#0.###");   
  
    public static String toBigAmt(double amount) {   
  
		  String temp="";
		  if(amount<0)
		  {
			   temp="负";
		  }
		  amount=Math.abs(amount);
        nf.setMinimumFractionDigits(3);//小数点后不足的补零   
        String amt = nf.format(amount);//将double类型的数格式化并转换成字符串,实际上进行了四舍五入   
  
        String dotPart = ""; //取小数位   
  
        String intPart = ""; //取整数位   
  
        int dotPos;   
        if ((dotPos = amt.indexOf('.')) != -1) {   
  
            intPart = amt.substring(0, dotPos);   
  
            dotPart = amt.substring(dotPos + 1);   
  
            if(dotPart.length()>4){ //超过4位直接截取   
  
                dotPart = dotPart.substring(0,4);   
  
            }   
  
        } else {   
  
            intPart = amt;   
  
        }   
  
        if (intPart.length() > 16)   
  
            throw new java.lang.InternalError("数额太大，无法转换。");   

        String intBig = intToBig(intPart);   
  
        String dotBig = dotToBig(dotPart);   
  
        //以下代码稍做修改，现在好多了。   
  
        if ((dotBig.length() == 0) && (intBig.length() != 0)) {   
  
            return temp+intBig + "元整";   
  
        } else if ((dotBig.length() == 0) && (intBig.length() == 0)) {   
  
            return temp+intBig + "零元";   
  
        } else if ((dotBig.length() != 0) && (intBig.length() != 0)) {   
  
            return temp+intBig + "元" + dotBig;   
  
        } else {   
  
            return temp+dotBig;   
  
        }   
  
    }   
  
  
  
    /**  
 
     * 用来处理几角几分几厘  
 
     * @param dotPart  
 
     * @return  
 
     */  
  
    private static String dotToBig(String dotPart) {   
  
        //得到转换后的大写（小数部分）   
  
        String strRet = "";   
  
        for (int i = 0; i < dotPart.length() && i < 3; i++) {   
  
            int num;   
  
            if ((num = Integer.parseInt(dotPart.substring(i, i + 1))) != 0)   
  
                strRet += NUM.substring(num, num + 1)   
  
                        + DOTUNIT.substring(i, i + 1);   
  
        }   
  
        return strRet;   
  
    }   
  
  
  
    /**  
 
     * 用来处理多少元 ，这个要仔细考虑才行  
 
     * @param intPart  
 
     * @return  
 
     */  
  
    private static String intToBig(String intPart) {   
  
        //得到转换后的大写（整数部分）   
  
        int grade; //级长   
  
        String result = "";   
  
        String strTmp = "";   
  
  
  
        //得到当级长   
  
        grade = intPart.length() / GRADE;   
  
        //调整级次长度   
  
        if (intPart.length() % GRADE != 0)   
  
            grade += 1;   
  
  
  
        //对每级数字处理，先处理最高级，然后再处理低级的   
  
        for (int i = grade; i >= 1; i--) {   
  
            strTmp = getNowGradeVal(intPart, i);//取得当前级次数字   
  
            result += getSubUnit(strTmp);//转换大写   
  
            //System.out.println(strTmp+"|"+getSubUnit(strTmp));   
  
            result = dropZero(result);//除零 去掉连续的零   
  
            //System.out.println("result="+result);   
  
            //加级次单位   
  
            if (i > 1) //末位不加单位   
  
                //单位不能相连续   
  
                //注意：连续4个零的时候要特殊处理(wmj修改此bug)   
  
                if(getSubUnit(strTmp).equals("零零零零")){   
  
                    result = result+"零";   
  
                }else{   
  
                    result += GRADEUNIT.substring(i - 1, i);   
  
                }   
  
        }   
  
        return result;   
  
    }   
  
  
  
    private static String getNowGradeVal(String strVal, int grade) {   
  
        //得到当前级次的串   
  
        String rst;   
  
        if (strVal.length() <= grade * GRADE)   
  
            rst = strVal.substring(0, strVal.length() - (grade - 1) * GRADE);   
  
        else  
  
            rst = strVal.substring(strVal.length() - grade * GRADE, strVal   
  
                    .length()   
  
                    - (grade - 1) * GRADE);   
  
        return rst;   
  
    }   
  
  
  
    private static String getSubUnit(String strVal) {   
  
        //数值转换   
  
        String rst = "";   
  
  
  
        for (int i = 0; i < strVal.length(); i++) {   
  
            String s = strVal.substring(i, i + 1);   
  
            int num = Integer.parseInt(s);   
  
            if (num == 0) {   
  
                //“零”作特殊处理   
  
                if (i != strVal.length()) //转换后数末位不能为零   
  
                    rst += "零";   
  
            } else {   
  
                //If IntKey = 1 And i = 2 Then   
  
                //“壹拾”作特殊处理   
  
                //“壹拾”合理   
  
                //Else   
  
                rst += NUM.substring(num, num + 1);   
  
                //End If   
  
                //追加单位   
  
                if (i != strVal.length() - 1)//个位不加单位   
  
                    rst += UNIT.substring(i + 4 - strVal.length(), i + 4  
  
                            - strVal.length() + 1);   
  
            }   
  
        }   
  
        return rst;   
  
    }   
  
  
  
    /**  
 
     *   
 
     * @param strVal  
 
     * @return  
 
     */  
  
    private static String dropZero(String strVal) {   
  
        //去除连继的“零”   
  
        String strRst;   
  
        String strBefore; //前一位置字符   
  
        String strNow; //现在位置字符   
  
  
  
        strBefore = strVal.substring(0, 1);   
  
        strRst = strBefore;   
  
  
  
        for (int i = 1; i < strVal.length(); i++) {   
  
            strNow = strVal.substring(i, i + 1);   
  
            if (strNow.equals("零") && strBefore.equals("零"))   
  
                ;//同时为零   
  
            else  
  
                strRst += strNow;   
  
            strBefore = strNow;   
  
        }   
  
  
  
        //末位去零   
  
        if (strRst.substring(strRst.length() - 1, strRst.length()).equals("零"))   
  
            strRst = strRst.substring(0, strRst.length() - 1);   
  
        return strRst;   
  
    }   
}
